package com.mjk.manager.gen.impl.ui;

import com.mjk.common.base.model.BaseEntity;
import com.mjk.common.core.jdbc.annotation.ExampleField;
import com.mjk.common.core.jdbc.annotation.Filed;
import com.mjk.common.core.jdbc.annotation.Id;
import com.mjk.common.core.jdbc.util.provider.SqlProvider;
import com.mjk.common.util.FileUtils;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.util.StrUtils;
import com.mjk.manager.gen.dto.GenDto;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * vue代码生成
 * @author Administrator
 *
 */
public class VueGenerate implements IUiGen{

	
	@Override
	public Class<?> createClass(GenDto model) {
		String tableName = getTableName(model);
		String webDir = model.getWebProjectPath()+model.getWebPath()+tableName.toLowerCase()+"\\";
		String listFileName =   "index.vue";
		String listM = getTableGenerate(model.getEntity()).replace("#model", tableName);
		FileUtils.write2File(webDir, listFileName, listM);
		
		String formFileName = tableName + "Form.vue";
		String formM = getDialogGenerate(model.getEntity()).replace("#model", tableName);
		FileUtils.write2File(webDir, formFileName, formM);
		return null;
	}
	/**
	 *
     */
	private String getTableGenerate(BaseEntity entity){
	        StringBuilder tabStr = new StringBuilder();
	        StringBuilder searchStr = new StringBuilder();
	        //获取examplefiled字段
        List<Field> fileds = SqlProvider.getValidTableFiled(entity);
			String idFiled = "";
	        for (Field f : fileds) {
	        	Filed filed = f.getAnnotation(Filed.class);
				String label = "";
				if(null == filed){
					label = f.getName();
				}else{
					label =ObjectUtils.isEmpty(filed.comment())?f.getName():filed.comment();
				}
				if(null!=f.getAnnotation(Id.class)) {
					idFiled = f.getName();
				}
        		ExampleField example = f.getAnnotation(ExampleField.class);
	        	if(null!=example) {
	        		if(null!=filed && Filed.FieldType.INPUT.equals(filed.type())) {//如果是input
	        			searchStr.append("        <el-input v-model=\"search.").append(f.getName()).append("\" placeholder=\"请输入").append(label).append("\" clearable></el-input>").append(WRAP);
	        		}else if(null!=filed && Filed.FieldType.DATA.equals(filed.type())) {
	        			searchStr.append("        <el-date-picker v-model=\"search.").append(f.getName()).append("\" type=\"date\" value-format=\"yyyy-MM-dd\" clearable></el-date-picker>").append(WRAP);
	        		}else if(null!=filed && Filed.FieldType.TIME.equals(filed.type())) {
	        			searchStr.append("        <el-time-select v-model=\"search.").append(f.getName()).append("\"   :picker-options= \"{start:'08:30',step:'00:15',end:'18:30'}\" placeholder=\"选择时间\" clearable></el-time-select>").append(WRAP);
	        		}else if(null!=filed && Filed.FieldType.TIMEDATA.equals(filed.type())) {
	        			searchStr.append("        <el-date-picker v-model=\"search.").append(f.getName()).append("\" type=\"datetime\" value-format=\"yyyy-MM-dd hh:mm:ss\" placeholder=\"选择时间\"  clearable></el-date-picker>").append(WRAP);
	        		}else if(null!=filed && Filed.FieldType.SELECT.equals(filed.type())) {
	        			searchStr.append("        <sc-select v-model=\"search.").append(f.getName()).append("\" :apiObj=\"$API.api.request\"  clearable filterable style=\"width: 100%;\"  ></sc-select>").append(WRAP);
	        		}else{
						searchStr.append("        <el-input v-model=\"search.").append(f.getName()).append("\" placeholder=\"请输入").append(label).append("\" clearable></el-input>").append(WRAP);
					}
	        	}
	        	tabStr.append(TAB + "<el-table-column label=\"").append(label).append("\" prop=\"").append(f.getName()).append("\" ></el-table-column>").append(WRAP);
	        }
	        String tableName = getTableName(entity);
        	return "<template>" +WRAP+
	                "  <el-container>" +WRAP+
	                "    <el-header>" +WRAP+
	                "      <div class=\"left-panel\">" +WRAP+
	                "        <el-button v-if=\"isadmin\"  type=\"primary\" icon=\"el-icon-plus\" @click=\"add\"></el-button>" +WRAP+
	                "        <el-button v-show=\"false\" type=\"danger\" plain icon=\"el-icon-delete\" ></el-button>" +WRAP+
	                "      </div>" +WRAP+
	                "      <div class=\"right-panel\">" +WRAP+
	                "        <div class=\"right-panel-search\">" +WRAP+WRAP+
					searchStr +WRAP+
					"        <el-button type=\"primary\" icon=\"el-icon-search\" @click=\"refreshTable\" style=\"margin-left: 7px\"></el-button>" +WRAP+
	                "        </div>" +WRAP+
	                "      </div>" +WRAP+
	                "    </el-header>" +WRAP+
	                "    <el-main class=\"nopadding\">" +WRAP+
					"      <scTable ref=\"table\" :apiUrl=\"apiurl\" :column=\"column\" :params=\"search\"  @selection-change=\"selectionChange\" stripe remoteSort remoteFilter>"+WRAP+
	                "        <!--"+TAB_3+"<el-table-column type=\"selection\" width=\"50\"></el-table-column>-->" +WRAP+
	                "		 <!--"+TAB_3+"<el-table-column label=\"ID\" prop=\"id\"  fixed></el-table-column>-->" +WRAP+
	                tabStr +WRAP+
	                "        <el-table-column label=\"操作\"  v-if=\"isadmin\"  fixed=\"right\" align=\"left\" min-width=\"140\">" +WRAP+
	                "          <template  #default=\"scope\">" +WRAP+
	                "            <el-button type=\"primary\" size=\"small\" plain @click=\"edit(scope.row)\">编辑</el-button>" +WRAP+
	                "            <el-popconfirm :title=\"'确定删除吗？'\" @confirm=\"doDel(scope.row."+idFiled+", scope.$index)\">" +WRAP+
	                "              <template #reference>" +WRAP+
	                "                <el-button type=\"danger\" size=\"small\" plain>删除</el-button>" +WRAP+
	                "              </template>" +WRAP+
	                "            </el-popconfirm>" +WRAP+
	                "          </template>" +WRAP+
	                "        </el-table-column>" +WRAP+
	                "      </scTable>" +WRAP+
	                "    </el-main>" +WRAP+
	                "  </el-container>" +WRAP+WRAP+
	                "  <#modelForm v-if=\"showDialog\" ref=\"#modelForm\"  @success=\"handleSaveSuccess\" @closed=\"showDialog=false\"></#modelForm>" +WRAP+WRAP+
	                "</template>" +WRAP+WRAP+
	                "<script>" +WRAP+
	                //"import tool from \"@/utils/tool\";" +WRAP+
	                "import #modelForm from \"./#modelForm\"" +WRAP+
	                "export default {" +WRAP+
	                SPACE+" name: '#modelList'," +WRAP+
	                SPACE+" components: {#modelForm}," +WRAP+
	                SPACE+" data() {" +WRAP+
	                TAB+" return {" +WRAP+
	                TAB+SPACE+" isadmin: true," +WRAP+
	                TAB+SPACE+" search: {keyword: \"\"}," +WRAP+
	                TAB+SPACE+" apiurl:this.$CONFIG.API_URL+\"/common/v1/"+tableName.toLowerCase()+"?method=get"+ StrUtils.toUpperCaseFirstOne(tableName)+"List\"," +WRAP+
	                TAB+SPACE+" delurl:this.$CONFIG.API_URL+\"/common/v1/"+tableName.toLowerCase()+"?method=del"+StrUtils.toUpperCaseFirstOne(tableName)+"\"," +WRAP+
	                TAB+SPACE+" list: []," +WRAP+
	                TAB+SPACE+" showDialog: false," +WRAP+
	                TAB+" }" +WRAP+
	                SPACE+" }," +WRAP+
	                SPACE+" methods: {" +WRAP+
	                TAB+" refreshTable() {" +WRAP+
	                TAB+SPACE+" this.$refs.table.refresh()" +WRAP+
	                TAB+" }," +WRAP+
	                TAB+" add() {" +WRAP+
	                TAB+SPACE+" this.showDialog = true;" +WRAP+
	                TAB+SPACE+" this.$nextTick(() => {" +WRAP+
	                TAB_2+" this.$refs.#modelForm.open();" +WRAP+
	                TAB+SPACE+" })" +WRAP+
	                TAB+" }," +WRAP+
	                TAB+" edit(row) {" +WRAP+
	                TAB+SPACE+" this.showDialog = true;" +WRAP+
	                TAB+SPACE+" this.$nextTick(() => {" +WRAP+
	                TAB_2+" this.$refs.#modelForm.open('edit').setData(row);" +WRAP+
	                TAB+SPACE+" })" +WRAP+
	                TAB+" }," +WRAP+
	                TAB+" async doDel(id, index) {" +WRAP+
	                TAB_2+" var res = await this.$API.demo.post.post(this.delurl,{"+idFiled+": id});" +WRAP+
					TAB_2+"  if(res.code == 1){" +WRAP+
	                TAB_3+" this.$refs.table.removeIndex(index);" +WRAP+
	                TAB_3+" this.$message.success('操作成功');" +WRAP+
					TAB_2+"}else{"+WRAP+
					TAB_3+"this.$message.warning(res.msg)" +WRAP+
					TAB_2+"}"+WRAP+
	                TAB+" }," +WRAP+
	                TAB+" //本地更新数据" +WRAP+
	                TAB+" handleSaveSuccess(data, mode) {" +WRAP+
	                TAB+SPACE+" //为了减少网络请求，直接变更表格内存数据" +WRAP+
	                TAB+SPACE+" if (mode == 'add') {" +WRAP+
	                TAB_2+" this.$refs.table.unshiftRow(data)" +WRAP+
	                TAB+SPACE+" } else if (mode == 'edit') {" +WRAP+
	                TAB_2+" this.$refs.table.updateKey(data)" +WRAP+
	                TAB+SPACE+" }" +WRAP+
	                TAB+SPACE+" //当然也可以暴力的直接刷新表格" +WRAP+
	                TAB+SPACE+" // this.$refs.table.refresh()" +WRAP+
	                TAB+" }," +WRAP+
	                SPACE+" }," +WRAP+
	                SPACE+" created() {" +WRAP+
	                //TAB+" if (stringutil.getRoleType() === \"admin\" || (stringutil.getAccount().roleId == 1)) {" +WRAP+
	                //TAB+SPACE+" this.isadmin = true;" +WRAP+
	                //TAB+" }" +WRAP+
	                SPACE+" }" +WRAP+
	                "}" +WRAP+
	                "</script>" +WRAP+
	                "<style>" +WRAP+
	                "</style>\n";
	    }
	
	public String getDialogGenerate(BaseEntity entity){
        StringBuilder fieldStr= new StringBuilder();
        String tableName = getTableName(entity);
        List<Field> fileds = SqlProvider.getValidTableFiled(entity);
        for (Field f : fileds) {
        	Filed filed = f.getAnnotation(Filed.class);
			String label = "";
			if(null == filed){
				label = f.getName();
			}else{
				label = ObjectUtils.isEmpty(filed.comment())?f.getName():filed.comment();
			}
        	ExampleField example = f.getAnnotation(ExampleField.class);
        	fieldStr.append(TAB_2 + " <el-form-item label=\"*").append(label).append("\">").append(WRAP);
        	if(null!=example) {
        		if(null!=filed && Filed.FieldType.INPUT.equals(filed.type())) {//如果是input
        			fieldStr.append(TAB_3 +"<el-input v-model=\"form.").append(f.getName()).append("\" placeholder=\"请输入").append(label).append("\" clearable></el-input>").append(WRAP);
        		}else if(null!=filed && Filed.FieldType.DATA.equals(filed.type())) {
        			fieldStr.append(TAB_3 +"<el-date-picker v-model=\"form.").append(f.getName()).append("\" type=\"date\" value-format=\"yyyy-MM-dd\" clearable></el-date-picker>").append(WRAP);
        		}else if(null!=filed && Filed.FieldType.TIME.equals(filed.type())) {
        			fieldStr.append(TAB_3 +"<el-time-select v-model=\"form.").append(f.getName()).append("\"   :picker-options= \"{start:'08:30',step:'00:15',end:'18:30'}\" placeholder=\"选择时间\" clearable></el-time-select>").append(WRAP);
        		}else if(null!=filed && Filed.FieldType.TIMEDATA.equals(filed.type())) {
        			fieldStr.append(TAB_3 +"<el-date-picker v-model=\"form.").append(f.getName()).append("\" type=\"datetime\" value-format=\"yyyy-MM-dd hh:mm:ss\" placeholder=\"选择时间\"  clearable></el-date-picker>").append(WRAP);
        		}else if(null!=filed && Filed.FieldType.SELECT.equals(filed.type())) {
        			fieldStr.append(TAB_3 +"<sc-select v-model=\"form.").append(f.getName()).append("\" :apiObj=\"$API.api.request\"  clearable filterable style=\"width: 100%;\"  ></sc-select>").append(WRAP);
        		}else{
					fieldStr.append(TAB_3 +"<el-input v-model=\"form.").append(f.getName()).append("\" placeholder=\"请输入").append(label).append("\" clearable></el-input>").append(WRAP);
				}
        	}else {
        		//根据数据返回值 判断属性
        		String typeName = f.getGenericType().getTypeName();
        		if(String.class.getName().equals(typeName)){
        			fieldStr.append(TAB_3 + " <el-input v-model=\"form.").append(f.getName()).append("\"></el-input>").append(WRAP);
        		}else if(Integer.class.getName().equals(typeName)||Float.class.getName().equals(typeName)||
        					BigDecimal.class.getName().equals(typeName)) {
        			fieldStr.append(TAB_3 + " <el-input v-model=\"form.").append(f.getName()).append("\" oninput=\"if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}\" maxLength='9'></el-input>").append(WRAP);
        		}else if(Date.class.getName().equals(typeName)) {
        			fieldStr.append(TAB_3 + "<el-date-picker v-model=\"form.").append(f.getName()).append("\" type=\"datetime\" value-format=\"yyyy-MM-dd hh:mm:ss\" placeholder=\"选择时间\"  clearable></el-date-picker>").append(WRAP);
        		}else {
        			fieldStr.append(TAB_3 + " <el-input v-model=\"form.").append(f.getName()).append("\"></el-input>").append(WRAP);
        		}
        	}
        	fieldStr.append( TAB_2+" </el-form-item>"+WRAP);
        }
        return "<template>" +WRAP+
                SPACE+" <el-dialog" +WRAP+
                TAB+" :title=\"titleMap[mode]\"" +WRAP+
                TAB+" v-model=\"visible\"" +WRAP+
                TAB+" :width=\"500\"" +WRAP+
                TAB+" @closed=\"$emit('closed')\"" +WRAP+
                TAB+" destroy-on-close>" +WRAP+
                TAB+" <el-main>" +WRAP+
                TAB+SPACE+" <el-form ref=\"form\" :model=\"form\" label-width=\"100px\" status-icon>" +WRAP+WRAP+
                fieldStr+WRAP+
                TAB_2+" <el-form-item>" +WRAP+
                TAB_3+" <el-button type=\"primary\" @click=\"doSave\">保存</el-button>" +WRAP+
                TAB_3+" <el-button @click=\"visible=false\">取消</el-button>" +WRAP+
                TAB_2+" </el-form-item>" +WRAP+
                TAB+SPACE+" </el-form>" +WRAP+
                TAB+" </el-main>" +WRAP+
                SPACE+" </el-dialog>" +WRAP+
                "</template>" +WRAP+WRAP+
                "<script>" +WRAP+WRAP+
                "export default {" +WRAP+
                SPACE+" name: '#modelForm'," +WRAP+
                SPACE+" data() {" +WRAP+
                TAB+" return {" +WRAP+
                TAB+SPACE+" // categoryId:''," +WRAP+
                TAB+SPACE+" form: {}," +WRAP+
                TAB+SPACE+" saveurl:this.$CONFIG.API_URL+\"/common/v1/"+tableName.toLowerCase()+"?method=saveOrUpdate"+StrUtils.toUpperCaseFirstOne(tableName)+"\"," +WRAP+
                TAB+SPACE+" mode: 'add'," +WRAP+
                TAB+SPACE+" visible: false," +WRAP+
                TAB+SPACE+" titleMap: {" +WRAP+
                TAB_2+" add: '新增'," +WRAP+
                TAB_2+" edit: '编辑'," +WRAP+
                TAB+SPACE+" }," +WRAP+
                TAB+" }" +WRAP+
                SPACE+" }," +WRAP+
                SPACE+" methods: {" +WRAP+
                TAB+" //显示" +WRAP+
                TAB+" open(mode = 'add') {" +WRAP+
                TAB+SPACE+" this.mode = mode;" +WRAP+
                TAB+SPACE+" this.visible = true;" +WRAP+
                TAB+SPACE+" return this;" +WRAP+
                TAB+" }," +WRAP+
                TAB+" setData(data) {" +WRAP+
                TAB+SPACE+" Object.assign(this.form, data);" +WRAP+
                TAB+" }," +WRAP+
                TAB+" async doSave() {" +WRAP+
                //TAB+SPACE+" try {" +WRAP+
                TAB_2+" var res = await this.$API.demo.post.post(this.saveurl,this.form);" +WRAP+
				TAB_2+"if(res.code == 1){" +WRAP+
				TAB_2+"this.visible = false;" +WRAP+
				TAB_3+"this.$message.success('保存成功');" +WRAP+
				TAB_2+"}else{" +WRAP+
				TAB_3+"this.$message.warning(res.msg);" +WRAP+
				TAB_2+"}" +WRAP+
//                TAB_2+" if (this.mode == 'add') {" +WRAP+
//                TAB_3+" this.form.id = res.data.id;" +WRAP+
//                TAB_3+" this.form.created = res.data.created.slice(0, 19);" +WRAP+
//                TAB_2+" }" +WRAP+
//                TAB_2+" this.$emit('success', this.form, this.mode);" +WRAP+
//                TAB_2+" this.visible = false;" +WRAP+
//                TAB_2+" this.$message.success('保存成功');" +WRAP+
//                TAB+SPACE+" } catch (err) {" +WRAP+
//                TAB_2+" this.$message.error(err.msg);" +WRAP+
//                TAB+SPACE+" }" +WRAP+
                TAB+" }," +WRAP+
//                TAB+" async getDict() {" +WRAP+
//                TAB+SPACE+" var res = await this.$API.common.getDict.get({keys: 'enable'});" +WRAP+
//                TAB+SPACE+" // this.enableList = res.data.enableList;" +WRAP+
//                TAB+" }," +WRAP+
                SPACE+" }," +WRAP+
                SPACE+" created() {" +WRAP+WRAP+
                SPACE+" }" +WRAP+
                "}" +WRAP+
                "</script>" +WRAP+WRAP+
                "\n";
    }
}
